#include "code.h"
#include "assert.h"

/* set address of a list of quads in the code list */
void backpatch(intList quadRefs,unsigned long int addr)
{
  /* this funtion has a terrible complexity, but well */
  intList tmp=quadRefs;
  while (tmp)
    {
      setAddr(tmp->head,addr);
      tmp=tmp->tail;
    }
  /* we free the list */
  freeintList(quadRefs);
}

/* set address of a quad in the code list */
void setAddr(unsigned long int quadRef,unsigned long int addr)
{
  unsigned long int counter=0;
  quadList tmp=CODE.list;

  /* we don't check for null, it should never happen */
  while(counter<quadRef)
    {
      assert(tmp);
      tmp=tmp->tail;
      counter++;
    }
  tmp->head.a3=(void*)addr;
}

void setEntryPoint(unsigned long int addr)
{
  CODE.list->head.a3=(void*)addr;
}

unsigned long int gen(quad q)
{
  quadList tmp=CODE.list;
  quadList newQ=malloc(sizeof(*newQ));
  newQ->head=q;
  newQ->tail=NULL;
  if (tmp)
    {
      while(tmp->tail)
	{
	  tmp=tmp->tail;
	}
      tmp->tail=newQ;
    }
  else
    {
      CODE.list=newQ;
    }
  NEXTQUAD++;
  return (NEXTQUAD-1);
}

void initCode()
{
  CODE.list=NULL;
  /* our entry point  */
  gen(newQuad(Q_GOTO,NULL,NULL,NULL));
  NEXTQUAD=1;
}
void printCode()
{
  quadList tmp=CODE.list;
  unsigned long int index=0;
  while(tmp)
    {
      printf("%li:\t",index);
      index++;
      printQuad(tmp->head);
      tmp=tmp->tail;
    }
}
